import styles from './style.less';
import { history } from 'umi';
import ContentLayout from '@/layouts/ContentLayout'
import { Table, Button, Tag, Form, DatePicker, Modal, Input, message } from 'antd'
import { useState } from 'react';
import ArrayUtils from '@/utils/ArrayUtils'
import { PROJECT_DEV_STATUS, IS_ARCHVE } from '@/consts/project'
import CheckActon from '@/pages/projects/components/CheckActoin'
import UserBrief from '@/components/UserBrief'
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import ActionDropdown from '@/components/ActionDropdown';
import { formetDate, formetTime_MDHm } from '@/utils/dateUtils'
import { useEffect } from 'react';
import ProjectProdSelect from '@/pages/projects/components/ProjectProduct/ProjectProdSelect'
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
import { pageDev, save } from '@/services/project/dev'


export const DevStatus = (props) => {
    const {
        status
    } = props

    if (status || status === 0) {
        return <Tag color={PROJECT_DEV_STATUS[status]?.color}>{PROJECT_DEV_STATUS[status]?.name}</Tag>
    }
    return (
        <Tag>/</Tag>
    )
}

const DevPage = (props) => {

    const {
        projectId,
        showProdColumn = true,
        onQueryParamChange,
        projectPermission,
        queryInitParams = {},
    } = props;

    const [params, setParams] = useState({
        pageSize: 10,
        pageNum: 1
    });
    const [isNewDevModalVisiable, setIsNewDevModalVisiable] = useState(false);
    const [form] = Form.useForm();
    const [devPageData, setDevPageData] = useState();
    const [devPageDataLoading, setDevPageDataLoading] = useState(false)
    const [permission, setPermission] = useState();

    useEffect(() => {
        let initParams = {
            ...params,
            ...queryInitParams,
        }
        setParams(initParams)

        if (projectId) {
            queryDevPage(initParams)
        }
    }, [projectId])

    useEffect(() => {
        setPermission({
            ...projectPermission?.dev
        })
    }, [projectPermission])


    const showDevDetail = (id) => {
        history.push(`/projects/${projectId}/dev/${id}`)
    }

    const queryDevPage = (queryParams) => {
        console.log(queryParams)
        setDevPageDataLoading(true)
        pageDev(projectId, (queryParams || params)).then(({ data }) => {
            setDevPageData(data)
            setDevPageDataLoading(false)
        })

    }

    const tableColumns = [{
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        width: "20%",
        fixed: 'left',
        ellipsis: {
            showTitle: true
        },
        sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: "10%",
        sorter: (a, b) => a.status - b.status,
        render: (text, record) => <DevStatus status={record.status} />,
    },
    {
        title: '所属迭代',
        dataIndex: 'projectProdItemId',
        key: 'projectProdItemId',
        width: "10%",
        ellipsis: {
            showTitle: true
        },
        render: (text, record) => record.projectProdItem && record.projectProdItem.name,
    },
    {
        title: '负责人',
        dataIndex: 'userId',
        key: 'userId',
        width: "14%",
        render: (text, record) => <UserBrief user={record.user}></UserBrief>,
    },
    {
        title: '开始时间',
        dataIndex: 'actualStartDate',
        key: 'actualStartDate',
        width: "96px",
        render: (text, record) => formetDate(record.actualStartDate) || formetDate(record.planStartDate),
        sorter: (a, b) => a.createTime.localeCompare(b.createTime),
    },
    {
        title: '提测时间',
        dataIndex: 'actualSubmitQaDate',
        key: 'actualSubmitQaDate',
        width: "96px",
        render: (text, record) => formetDate(record.actualSubmitQaDate) || formetDate(record.planSubmitQaDate),
        sorter: (a, b) => a.createTime.localeCompare(b.createTime),
    },
    {
        title: '发布时间',
        dataIndex: 'actualReleaseDate',
        key: 'actualReleaseDate',
        width: "96px",
        render: (text, record) => formetDate(record.actualReleaseDate) || formetDate(record.planReleaseDate),
        sorter: (a, b) => a.createTime.localeCompare(b.createTime),
    },
    {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: "18%",
        sorter: (a, b) => a.createTime.localeCompare(b.createTime),
        render: (text, record) => formetTime_MDHm(record.createTime),
        defaultSortOrder: 'descend'
    }];

    const queryItems = [{
        name: "inStatus",
        label: "状态",
        isMain: true,
        type: "tagSelect",
        options: ArrayUtils.jsonToArray(PROJECT_DEV_STATUS).map((item) => ({
            value: item.key,
            label: item.value.name
        }))
    },
    {
        name: "likeName",
        label: "名称",
        isMain: true,
        span: 8,
        type: "input",
    },
    {
        name: "inUserId",
        label: "负责人",
        isMain: true,
        span: 8,
        type: "userSelect",
    }, {
        name: "inProjectProdItemId",
        label: "迭代",
        isMain: true,
        span: 8,
        type: "custom",
        render: () => {
            return <ProjectProdSelect
                allowClear={true}
                ismultiple={true}
                onChange={(value) => {
                    onParamChange({
                        inProjectProdItemId: value
                    }, true)
                }}
                projectId={projectId} />
        }
    }];

    const actionHeader = [
        <ActionDropdown
            key="actions"
            status={params?.isArchived && "filter"}
            placement="bottomRight"
            actions={[
                <CheckActon
                    check={params?.isArchived === 1}
                    onChange={(value) => {
                        if (value) {
                            onParamChange({
                                isArchived: 1
                            }, true)
                        } else {
                            onParamChange({
                                isArchived: null
                            }, true)
                        }
                    }}
                    label={'查看归档数据'}
                />,
            ]}
        />,
        permission?.add && <Button type="primary" size="middle" onClick={() => {
            setIsNewDevModalVisiable(true)
        }}> 新增 </Button>
        ,
        <CheckActon
            check={params?.mySelection === 1}
            onChange={(value) => {
                if (value) {
                    onParamChange({
                        mySelection: 1
                    }, true)
                } else {
                    onParamChange({
                        mySelection: null
                    }, true)
                }
            }}
            label={'只看我的'}
        />];

    const onParamChange = (param, doQuery) => {
        if (param && !param.pageNum) {
            param.pageNum = 1;
        }
        let newParams = { ...params, ...param }
        setParams(newParams)
        if (onQueryParamChange) {
            onQueryParamChange(newParams)
        }
        if (doQuery) {
            queryDevPage(newParams)
        }
    }

    const filterColumn = (tableColumns) => {
        let showColumns
        if (!showProdColumn) {
            showColumns = tableColumns.filter(column => column.key !== 'projectProdItemId')
        } else {
            showColumns = tableColumns;
        }
        return showColumns
    }

    const saveNewDev = async () => {
        const values = await form.validateFields();
        console.log(values)
        const data = {
            ...values
        }
        if (values.planDate) {
            data.planStartDate = formetDate(values.planDate[0]);
            data.planSubmitQaDate = formetDate(values.planDate[1]);
            data.planDate = undefined
        }
        save(projectId, data).then(({ success }) => {
            if (success) {
                message.success("保存成功！")
                setIsNewDevModalVisiable(false);
                form.resetFields();
                queryDevPage();
            }
        })
    }

    return <>
        <ContentLayout
            queryItems={queryItems}
            actionHeader={actionHeader}
            queryInitParams={queryInitParams}
            onQueryChange={onParamChange}
            content={
                <Table
                    onChange={(pagination, filters, sorter) => {
                        onParamChange({
                            pageNum: pagination.pageSize === params.pageSize ? pagination.current : 1,
                            pageSize: pagination.pageSize
                        }, true)
                    }}
                    columns={filterColumn(tableColumns)}
                    rowKey="id"
                    loading={devPageDataLoading}
                    dataSource={devPageData && devPageData.list}
                    pagination={{
                        position: ["bottomCenter"],
                        showSizeChanger: true,
                        pageSize: params.pageSize || 10,
                        total: devPageData && devPageData.count,
                        current: devPageData && devPageData.pageNum,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total, range) => `总数： ${total} `
                    }}
                    size="small"
                    onRow={record => {
                        return {
                            onClick: () => {
                                showDevDetail(record.id)
                            }
                        }
                    }}
                >
                </Table>
            }
        >

        </ContentLayout>
        <Modal
            visible={isNewDevModalVisiable}
            closable
            title={"新增开发项"}
            onCancel={() => {
                setIsNewDevModalVisiable(false)
            }}
            onOk={() => {
                saveNewDev();
            }}
            destroyOnClose
            okText={"确认"}
            cancelText={"取消"}
        >
            <Form
                form={form}
                labelAlign="right"
                labelCol={{ span: 4 }}
            >
                <FormItem
                    label={"名称"}
                    name="name"
                    rules={[
                        {
                            required: true,
                            message: "请输入名称",
                        },
                    ]}
                >
                    <Input placeholder={"请输入名称"} maxLength={20} ></Input>
                </FormItem>
                <FormItem
                    label={"所属迭代"}
                    name="projectProdItemId"
                >
                    <ProjectProdSelect
                        projectId={projectId} />
                </FormItem>
                <FormItem
                    label={"负责人"}
                    name="userId"
                    rules={[
                        {
                            required: true,
                            message: "请选择负责人",
                        },
                    ]}
                >
                    <EnterpriseUserSelect projectId={projectId} ></EnterpriseUserSelect>
                </FormItem>
                <Form.Item name="planDate" label={"预计时间"}>
                    <RangePicker format="YYYY-MM-DD" />
                </Form.Item>
                <FormItem label={"描述"}
                    name="description"
                    rules={[
                        {
                            required: true,
                            message: "请输入描述",
                        },
                    ]}
                >
                    <Input.TextArea placeholder="请输入描述" maxLength={200} showCount>
                    </Input.TextArea>
                </FormItem>
            </Form>
        </Modal>

    </>
}

export default DevPage